package com.weitu.accidentEvent.accident.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accidentEvent.accident.service.AccidentMonthReportService;
import com.weitu.accidentEvent.accident.service.AccidentReportService;
import com.weitu.base.controller.BaseController;
import com.weitu.permission.user.entity.User;
import com.weitu.util.AjaxResult;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.IProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * 事故月报
 * Created by fanyuting on 2017/5/19 0019.
 */
@Controller
@RequestMapping("accidentEvent/accidentMonthReport")
public class AccidentMonthReportController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "accidentEvent/accidentMonthReport/";
    @Autowired
    private AccessoryUtilService accessoryUtilService;//附件
    @Autowired
    private AccidentReportService accidentReportService;//事故报告service
    @Autowired
    private AccidentMonthReportService accidentMonthReportService;//事故月报service
    @Autowired
    private FlowManagementService flowManagementService;//流程管理service
    private WorkflowReview workflowReview;

    public WorkflowReview getWorkflowReview() {
        return workflowReview;
    }

    /**
     * 跳转到月报列表页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String toAccidentMonthReportListPage(Model model) {
        return MODULE_BATH_PATH + "list";
    }

    /**
     * 跳转到新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String toAccidentMonthReportAddPage(Model model) {
        return MODULE_BATH_PATH + "add";
    }

    /**
     * 跳转到详情页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public String toAccidentMonthReportDetailPage(HttpServletRequest request, Model model) {
        String businessId = this.getPara("businessId");
        Map<String, Object> info = this.accidentMonthReportService.queryInfoById(businessId);
        model.addAttribute("info", info);
        return MODULE_BATH_PATH + "detail";
    }

    /**
     * 查询月报列表信息
     */
    /**
     * 查询分页列表数据
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("queryMonthReportList")
    public Object queryMonthReportList(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        //获取前台参数
        putParametersIntoMap(map);
        List<Map<String, Object>> list = this.accidentMonthReportService.queryMonthReport(map);
        return list;
    }

    /**
     * 验证月报是否重复
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyMonthReport")
    public Object verifyMonthReport(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        putParametersIntoMap(map);
        return this.accidentMonthReportService.verifyMonthReport(map);

    }

    /**
     * 保存事故月报信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/addMonthReportInfo")
    @Transactional
    public AjaxResult addMonthReportInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap();
        getAddBasicFieldMap(map);
        boolean flag = this.accidentMonthReportService.addInfo(map);
        if (flag) {
            return success("事故月报保存成功！");
        }
        return fail("事故月报保存失败！");
    }

     /*==============业务审批流程相关controller=======================*/

    /**
     * 提交审批
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitApplication", method = RequestMethod.POST)
    public AjaxResult submitApplication(HttpServletRequest request) throws Exception {
        User crrentUser = this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();
        putParametersIntoMap(paramMap);

        String businessId = paramMap.get("id").toString();//业务id
        String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
        //获取事故信息
        //Accident info = this.accidentService.queryInfoById(businessId);
        // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        //启动流程实例
        IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_AE_ACCIDENTMONTHREPORT, businessId, "事故月报信息", nextUserId);
        //int i=1/0;
        boolean appStateFlag = false;
        if (processInstance != null) {
            appStateFlag = this.accidentMonthReportService.editAppState(businessId, "0");
        }

        if (appStateFlag) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /***
     * 跳转到信息审批页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toApplicationVerify")
    public ModelAndView toApplicationVerify(HttpServletRequest request) {
        User crrentUser = this.getSessionUser();
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        String businessId = paramMap.get("businessId").toString();//获取业务id，以businessId命名
        //工作项id
        String workItemId = paramMap.get("workItemId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType = paramMap.get("formType") != null ? Integer.parseInt(paramMap.get("formType").toString()) : 0;
        modelAndView.addObject("workItemId", workItemId);
        modelAndView.addObject("formType", formType);

        //获取意见信息
        WorkflowReview workflowReview = this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview", workflowReview);

        //查询事故信息
        Map<String, Object> info = this.accidentMonthReportService.queryInfoById(businessId);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        //步骤：第几步信息
        String step = request.getParameter("step");
        modelAndView.addObject("step", step);
        modelAndView.addObject("info", info);
        modelAndView.addObject("accessoryList", accessoryList);
        modelAndView.addObject("uploadUserId", crrentUser.getId());
        modelAndView.setViewName(MODULE_BATH_PATH + "verify");
        return modelAndView;
    }

    /**
     * 审批信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "verifyApplication")
    public AjaxResult verifyApplication(HttpServletRequest request) throws Exception {
        String businessId = request.getParameter("businessId");
        String workItemId = request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview = this.flowManagementService.getWorkflowReviewByRequest(request, "workflowReview", workItemId);
        //保存处理结果
        boolean boo = this.flowManagementService.saveWorkflowReview(workflowReview);
        //步骤：第几步信息
        String step = request.getParameter("step");
        //结束环节，继续流程向下执行
        if (boo) {
            //更改业务中的审批状态
            String result = workflowReview.getResult();
            if ("1".equals(result)) {
                if ("2".equals(step)) {
                    this.accidentMonthReportService.editAppState(businessId, "1");
                }
            } else {
                if ("2".equals(step)) {
                    this.accidentMonthReportService.editAppState(businessId, "-1");
                }

            }

            this.flowManagementService.workItemComplete(workItemId);
        }
        //打印工作流信息
        //System.out.println(workflowReview.getComments());

        AjaxResult result = new AjaxResult();
        if (boo) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }
}
